package com.eascs.admin.o2o.internal.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.service.IO2oLoanapplyDubboService;
import com.eascs.admin.common.utils.AccountConstants;
import com.eascs.admin.item.service.O2oPubDdItemService;
import com.eascs.admin.o2o.backFees.entity.O2oBackFeesEntity;
import com.eascs.admin.o2o.backFees.service.O2oBackFeesService;
import com.eascs.admin.o2o.badloan.service.O2oBadLoanService;
import com.eascs.admin.o2o.cacle.entity.O2oCacleFlowEntity;
import com.eascs.admin.o2o.cacle.service.O2oCacleFlowServiceImpl;
import com.eascs.admin.o2o.detail.controller.LoanDetailRestController;
import com.eascs.admin.o2o.enterpriseZX.entity.O2oEnterpriseZxEntity;
import com.eascs.admin.o2o.enterpriseZX.service.O2oEnterpriseZxService;
import com.eascs.admin.o2o.finance.entity.O2oFinanceFlowEntity;
import com.eascs.admin.o2o.finance.service.O2oFinanceFlowService;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpandDetail;
import com.eascs.admin.o2o.internal.form.PayMentForm;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandDetailService;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandService;
import com.eascs.admin.o2o.internal.service.PayMentService;
import com.eascs.admin.o2o.internal.service.WfTypeStatusService;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2OWorkFlowService;
import com.eascs.admin.o2o.loan.service.O2oChargeSituationService;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.loan.utils.BankRate;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oLoadUserZxServiceImpl;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.admin.o2o.recommend.entity.O2oRecommendEntity;
import com.eascs.admin.o2o.recommend.service.O2oRecommendService;
import com.eascs.admin.o2o.specialInterview.entity.O2OSpecialInterview;
import com.eascs.admin.o2o.specialInterview.service.O2OSpecialInterviewService;
import com.eascs.admin.o2o.zx.entity.O2oLoanUserEntityZx;
import com.eascs.admin.o2o.zx.entity.O2oZxEntity;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.crm.nsEditDetail.service.ContactsInfoService;
import com.eascs.crm.nsEditDetail.service.CustomerAssetInfoService;
import com.eascs.crm.nsEditDetail.service.CustomerShopInfoService;
import com.eascs.datalist.service.O2oDataListService;
import com.eascs.file.FileTypeConstants;
import com.eascs.gaczcontract.entity.CustomerBasicInfo;
import com.eascs.loan.service.O2oLoanService;
import com.eascs.pay.entity.O2oPayEntity;
import com.eascs.pay.service.impl.O2oPayServiceImpl;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.web.url.UrlHelper;
import com.eascs.workflow.WorkFlowConstants;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.sys.HREmployeeAuditor;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sys.EmployeeService;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;
import com.eascs.workflow.form.ZXPTCWForm;

/**
 * 
 * @author ycz 工作流 提交--Controller
 *
 */
/**
 * @ClassName: PayMentController
 * @Description: 
 * @author 张庆奇
 * @date 2017年10月16日 上午10:06:31
 * @version V1.0
 */
@Controller
@RequestMapping("/work")
public class PayMentController extends BaseRestController {
	private static final Logger logger = LoggerFactory.getLogger(PayMentController.class);
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Reference
	private WorkFlowService workFlowService;
	@Autowired
	private LoanapplyExpandService loanapplyExpandService;
	@Autowired
	private O2oDataListService o2oDataListService;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	@Autowired
	private  O2oPayServiceImpl o2oPayServiceImpl;
	@Autowired
	private  O2oFinanceFlowService financeFlowService;
	@Autowired
	O2oLoanService o2oLoanService;
	@Autowired
	private O2oBadLoanService            service;
	@Value("${o2o.admin.depositeUrl}")
	private String                       depositeUrl;
	@Autowired
	private LoanapplyExpandDetailService loanapplyExpandDetailService;
	@Autowired
	LoanDetailRestController loanDetailRestController;
	
	@Autowired
	O2oZxServiceImpl o2oZxServiceImpl;
	
	@Autowired
	O2oCacleFlowServiceImpl o2oCacleFlowServiceImpl;
	
	@Autowired
	O2oLoadUserZxServiceImpl o2oLoadUserZxServiceImpl;
	
	@Autowired
	O2OSpecialInterviewService o2OSpecialInterviewService;
	@Autowired
	O2OWorkFlowService o2oWorkFlowService;
	@Autowired
	O2oPubDdItemService o2oPubDdItemService;
	@Autowired
	ContactsInfoService contactsInfoService;
	@Autowired
	CustomerShopInfoService customerShopInfoService;
	@Autowired
	CustomerAssetInfoService customerAssetInfoService;
	@Autowired
	PayMentService payMentService;
	@Autowired
	O2oBackFeesService o2oBackFeesService;
	@Autowired
	O2oRecommendService o2oRecommendService;
	
	@Reference
	private SysOrgService sysOrgService;
	
	
	@Reference
	CustomerService customerService;
	
	@Reference
	EmployeeService employeeService;
	
	@Value("${o2o.admin.wf.zxUrl}")
	private String zxUrl;
	
	@Value("${o2o.admin.wf.nsUrl}")
	private String nsUrl;
	
	@Value("${o2o.admin.wf.sbzjUrl}")
	private String sbzjUrl;
	
	@Value("${o2o.admin.wf.cwshUrl}")
	private String cwshUrl;//财务审核详情页url
	
	@Value("${o2o.admin.wf.NewZxUrl}")
	private String NewZxUrl;
	
	@Value("${o2o.admin.wf.NewQYZxUrl}")
	private String NewQYZxUrl;
	
	@Value("${o2o.admin.wf.NewTXUrl}")
	private String NewTXUrl;
	@Value("${o2o.admin.wf.NewCacleUrl}")
	private String NewCacleUrl;
	
	@Value("${o2o.admin.wf.recommendUrl}")
	private String recommendUrl;
	
	
	@Autowired
	O2oEnterpriseZxService o2oEnterpriseZxService;
	
	@Autowired
	O2oChargeSituationService o2oChargeSituationService;
	@Autowired
	WfTypeStatusService wfTypeStatusService;
	
	/**
	 * 提交客户推荐管理
	 * 
	 * @return
	 */
	@RequestMapping(value = "/recommendStart")
	//@Transactional(transactionManager = "o2oTransactionManager")
	public BaseRestResult<String> recommendStart(PayMentForm payform) {
		User user = UserHolder.getUser();
		O2oRecommendEntity  o2oRecommendEntity = o2oRecommendService.getById(payform.getLoanapplyNo());
		logger.info("提交客户推荐管理对象：{}", o2oRecommendEntity);
		
		if(o2oRecommendEntity==null){
			logger.info("客户推荐管理对象：{}", o2oRecommendEntity);
			return BaseRestResult.warn("数据库未查到客户推荐管理信息，请联系管理员");
		}
		
		if(!(StatusContexts.WFTYPE_STATUS_NEW.equals(o2oRecommendEntity.getBillStatus())
			|| StatusContexts.WFTYPE_STATUS_BH.equals(o2oRecommendEntity.getBillStatus())	
				)){
			return BaseRestResult.warn("该单不在新建状或驳回态下无法启动流程！");
		}
		
		WFRequestParam param = new WFRequestParam();
		param.setReferId(o2oRecommendEntity.getId());
		param.setReferCode(o2oRecommendEntity.getBillCode());
		
		param.setReferUrl(recommendUrl); //个人退款代办详情
		
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType("RECOMMEND_REFUND");
		param.setProcessVersion("v1");
		
		/**
		 * 开始节点 -提交人
		 */
		Map<String, List<String>> roleUserMap = new HashMap<>();  //指定流程节点由谁经办
		
		if(o2oRecommendEntity.getSqType().equals(StatusContexts.RECOMMENDSQ_TYPE_O)){
			param.setAppliedby(o2oRecommendEntity.getOperatorNo());
			param.setAppliedbyName(o2oRecommendEntity.getOperatorName());
			roleUserMap.put("KHTJJS",Arrays.asList(o2oRecommendEntity.getReferrerNo()));
		}else{
			param.setAppliedby(o2oRecommendEntity.getReferrerNo());
			param.setAppliedbyName(o2oRecommendEntity.getReferrerName());
			roleUserMap.put("KHTJJS",Arrays.asList(o2oRecommendEntity.getOperatorNo()));
		}
		
		roleUserMap.put("KHTJSCB",Arrays.asList("204606")); //定死为田海杰
		
		param.setRoleUserMap(roleUserMap);
		//ModelResult<ActOrgEntity> modelResult1 = sysOrgService.getUniquePlatformWithUser(user.getNo());
		ModelResult<ActOrgEntity> modelResult1 = sysOrgService.getUniquePlatformWithUser(user.getNo());
		if (!modelResult1.isSuccess()) {
			return BaseRestResult.warn(modelResult1.getErrMsg());
		}
		
		/*
		List<ActOrgEntity> actOrgList = sysOrgService.getLeafNodeByParentId(entity.getOrgProvinceId());
		if (actOrgList == null || actOrgList.size() == 0) {
			return BaseRestResult.warn("找不到经办平台，请联系管理员");
		}
		ActOrgEntity actOrgEntity = null;
		for (ActOrgEntity org : actOrgList) {
			if(org.getOrgLevel() == 4)
				actOrgEntity = org;
		}
		if (actOrgEntity == null) {
			return BaseRestResult.warn("找不到经办平台对应的省区金融部，请联系管理员");
		}
			*/
		param.setOrgNo(modelResult1.getModel().getUnitNo());
	
		StringBuffer appliedDes = new StringBuffer("客户姓名:");
		appliedDes.append(o2oRecommendEntity.getUserName());
		appliedDes.append("，推荐类型:"+o2oPubDdItemService.findPubdditemO2ONameByCode("recommendType", o2oRecommendEntity.getRecommendType()));
		param.setAppliedDes(appliedDes.toString());
		logger.info("提交个人退款，参数有id：【{}】，编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
				o2oRecommendEntity.getId(),o2oRecommendEntity.getBillCode(),"RECOMMEND_REFUND",param.getProcessType(),param.getOrgNo(),appliedDes.toString());
		
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			o2oRecommendEntity.setBillStatus(StatusContexts.WFTYPE_STATUS_RUN);
			o2oRecommendEntity.setSubmitNo(user.getNo());
			o2oRecommendEntity.setSubmitName(user.getCname());
			o2oRecommendEntity.setSubmitTime(new Date());
			o2oRecommendService.updateById(o2oRecommendEntity);
			return BaseRestResult.info("提交成功").andRedirect(UrlHelper.build("/recommend/list"));
		} else {
			logger.error("提交客户推荐流程失败，错误信息{}", modelResult.getDetailStack());
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
		
	}
	
	/**
	 * 提交客户推荐管理(保存并启动)
	 * 
	 * @return
	 */
	@RequestMapping(value = "/saveRecommendStart")
	public BaseRestResult<String> saveRecommendStart(O2oRecommendEntity o2oRecommendEntity) {
		int i = o2oRecommendService.saveorupdateEntity(o2oRecommendEntity);
		if(i>0){
			logger.info("保存对象成功[{}]", o2oRecommendEntity.getBillCode());
		}
		//保存成功，启动流程
		PayMentForm payform = new  PayMentForm();
		payform.setLoanapplyNo(o2oRecommendEntity.getId());
		return recommendStart(payform);//启动流程
	}
	
	@Autowired
	IO2oLoanapplyDubboService loanapplyDubboService;
	
	/**
	 * 提交作废(保存并启动)
	 * 
	 * @return
	 */
	@RequestMapping(value = "/newcacle")
	public BaseRestResult<String> newcacle(PayMentForm payform) {
		User user = UserHolder.getUser();
		O2oCacleFlowEntity  o2oCacleEntity ;
		
		o2oCacleEntity = o2oCacleFlowServiceImpl.getEntityByLoanApplyNo(payform.getLoanapplyNo());
		//新建一个作废流程的单
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(payform.getLoanapplyNo());
		
		if(o2oCacleEntity==null){
			o2oCacleEntity = new O2oCacleFlowEntity();
			o2oCacleEntity.setCreateId(user.getNo());
			o2oCacleEntity.setCreateName(user.getCname());
			o2oCacleEntity.setCreateDate(new Date());
			o2oCacleEntity.setCcStatus(StatusContexts.WFTYPE_STATUS_NEW);
			o2oCacleEntity.setBillCode(o2oZxServiceImpl.buildCode("CACLE"));
			//o2oCacleEntity.setBillCode(loan.getBillCode());
			o2oCacleEntity.setIsDel(StatusContexts.O2O_NO);
			o2oCacleEntity.setLoanapplyNo(payform.getLoanapplyNo());
			o2oCacleEntity.setCacleMessage(payform.gettRemark());
			o2oCacleFlowServiceImpl.add(o2oCacleEntity);
			
		}else{
			o2oCacleEntity.setCacleMessage(payform.gettRemark());
			o2oCacleFlowServiceImpl.update(o2oCacleEntity);
		}
		
		//O2oCacleFlowEntity o2oCacleEntity = o2oCacleFlowServiceImpl.getEntityById(payform.getLoanapplyNo());
		logger.info("手动作废对象：{}", o2oCacleEntity);
		
		O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loan.getLoanId(), loan.getLoanapplyNo());
		WFRequestParam param = new WFRequestParam();
		param.setReferId(o2oCacleEntity.getId());
		param.setReferCode(o2oCacleEntity.getBillCode());
		param.setReferUrl(NewCacleUrl);
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType("PROCESS_CACLE");
		param.setProcessVersion("v1");
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(loan.getLtd());
		StringBuffer appliedDes = new StringBuffer("手动作废姓名:");
		appliedDes.append(loanUser.getUserFullName());
		appliedDes.append("，贷款单号:"+loan.getBillCode());
		
		List<String> list=new ArrayList<String>();
		Map<String, List<String>> roleUserMap = new HashMap<>();  //指定流程节点由谁经办
		
		HREmployeeAuditor auditor=employeeService.getAuditorWithNoAndType(loan.getOperatorNo(), "RM");
		
		if(auditor!=null){
			roleUserMap.put(StatusContexts.ROLE_TYPE_QYJLSPR,Arrays.asList(auditor.getAuditorNo()));
			param.setRoleUserMap(roleUserMap);
		}else{
			list.add(StatusContexts.O2O_WF_CODE_CACLE_QYJLSPR);
			param.setExcludeNodeCodeList(list); //删除节点
		}
		
		param.setAppliedDes(appliedDes.toString());
		logger.info("提交手动作废，参数有征信id：【{}】，征信编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
				o2oCacleEntity.getId(),o2oCacleEntity.getBillCode(),ProcessTemplate.SYSTEM_MODULE_O2O,param.getProcessType(),loan.getLtd(),appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			o2oCacleEntity.setCcStatus(StatusContexts.WFTYPE_STATUS_RUN);
			o2oCacleFlowServiceImpl.update(o2oCacleEntity);
			return BaseRestResult.info("提交成功").andRedirect(UrlHelper.build("/cacle/detail?id="+o2oCacleEntity.getId()));
		} else {
			logger.error("提交手动作废失败，错误信息{}", modelResult.getDetailStack());
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
		
	}
	
	
	
	/**
	 * 提交个人退款
	 * 
	 * @return
	 */
	@RequestMapping(value = "/newTXstartup")
	//@Transactional(transactionManager = "o2oTransactionManager")
	public BaseRestResult<String> newTXstartup(PayMentForm payform) {
		O2oBackFeesEntity  o2oBackFeesEntity = o2oBackFeesService.queryById(payform.getLoanapplyNo());
		logger.info("贷款对象：{}", o2oBackFeesEntity);
		
		if(o2oBackFeesEntity==null){
			logger.info("贷款对象：{}", o2oBackFeesEntity);
			return BaseRestResult.warn("数据库未查到个人退款信息，请联系管理员");
		}
		
		if(!StatusContexts.WFTYPE_STATUS_NEW.equals(o2oBackFeesEntity.getStatus()) ){
			
			return BaseRestResult.warn("该单不在新建状态下无法启动流程！");
		}
		
		WFRequestParam param = new WFRequestParam();
		param.setReferId(o2oBackFeesEntity.getId());
		param.setReferCode(o2oBackFeesEntity.getBillCode());
		param.setReferUrl(NewTXUrl); //个人退款代办详情
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType("ACCOUNT_REFUND");
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(o2oBackFeesEntity.getLtd());
		StringBuffer appliedDes = new StringBuffer("姓名:");
		appliedDes.append(o2oBackFeesEntity.getLoanName());
		appliedDes.append("，金额:"+o2oBackFeesEntity.getBackMoney()+"元");
		param.setAppliedDes(appliedDes.toString());
		logger.info("提交个人退款，参数有id：【{}】，编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
				o2oBackFeesEntity.getId(),o2oBackFeesEntity.getBillCode(),"ACCOUNT_REFUND",param.getProcessType(),o2oBackFeesEntity.getLtd(),appliedDes.toString());
		
		BigDecimal balance =o2oChargeSituationService.getFreezeBalanceByLoanId(o2oBackFeesEntity.getLoanId());
		if(o2oBackFeesEntity.getBackMoney().compareTo(balance)>0){
			return BaseRestResult.warn("退款金额超出可用金额。");
		}
		
		if(o2oBackFeesEntity.getBackMoney().compareTo(BigDecimal.ZERO)==0){
			return BaseRestResult.warn("退款金额不能为0");
		}
		
		//先冻结在调用流程
		String reulst = o2oBackFeesService.ChargingDJ(o2oBackFeesEntity, AccountConstants.ACCOUNT_DJ);
		
		if(StringUtil.isNotBlank(reulst)&&(reulst.equals("SUCCESS")||reulst.equals("ERROR_UNIQUEUD_HAD"))){
			logger.info("提交调用数据账户冻结成功，{}", reulst);
			
			ModelResult<Boolean> modelResult = workFlowService.instance(param);
			if (modelResult.isSuccess() && modelResult.getModel()) {
				o2oBackFeesEntity.setStatus(StatusContexts.WFTYPE_STATUS_RUN);
				o2oBackFeesEntity.setSubmitId(user.getNo());
				o2oBackFeesEntity.setSubmitName(user.getCname());
				o2oBackFeesEntity.setSubmitDate(new Date());
				o2oBackFeesService.update(o2oBackFeesEntity);
				//o2oLoanapplyService.updateWorkFlowStatus(StatusContexts.O2O_ZX_BEGIN, o2oLoanapplyEntity.getLoanapplyNo());
				return BaseRestResult.info("提交个人退款成功").andRedirect(UrlHelper.build("/backfees/list"));
			} else {
				logger.error("提交个人退款失败，错误信息{}", modelResult.getDetailStack());
				return BaseRestResult.warn(modelResult.getErrMsg());
			}
			
		}else{
			logger.info("提交调用数据账户冻结失败，{}", reulst);
			return BaseRestResult.warn(reulst);
			//throw new RuntimeException("个人退款调用数据账户冻结失败");
		}
		
	}
	
	
	/**
	 * 提交企业征信
	 * 
	 * @return
	 */
	@RequestMapping(value = "/newQYZXstartup")
	public BaseRestResult<String> newQYZXstartup(PayMentForm payform) {
		
		O2oEnterpriseZxEntity o2oEnterpriseZxEntity = o2oEnterpriseZxService.getEntityById(payform.getLoanapplyNo());
		logger.info("贷款对象：{}", o2oEnterpriseZxEntity);
		
		if(o2oEnterpriseZxEntity==null){
			logger.info("贷款对象：{}", o2oEnterpriseZxEntity);
			return BaseRestResult.warn("数据库未查到改企业征信，请联系管理员");
		}
		
		if (!o2oDataListService.checkQYZXApply(o2oEnterpriseZxEntity.getId())){
			return BaseRestResult.warn("上传附件未齐全");
		}
		
		if(o2oEnterpriseZxEntity.getZxBank()==null){
			return BaseRestResult.warn("请选择征信银行后，再启动流程");
		}
		
		//一个自然月内在同一家银行仅能查询一次企业征信报告
		if(!StatusContexts.O2O_BANKTYPE_BC.equals(o2oEnterpriseZxEntity.getZxBank())){
			Boolean isMothSelected =o2oEnterpriseZxService.isMothSelectedQYZX(o2oEnterpriseZxEntity.getZxTyshxydm(), o2oEnterpriseZxEntity.getZxBank());
			if(isMothSelected){
				return BaseRestResult.warn("一个自然月内在同一家银行仅能查询一次企业征信报告");
			}
		}
		
		WFRequestParam param = new WFRequestParam();
		
		
		Map<String, List<String>> roleUserMap = new HashMap<>();  //指定流程节点由谁经办
		//区域经理
		roleUserMap.put(StatusContexts.ROLE_TYPE_QYJLSPR,Arrays.asList(o2oEnterpriseZxEntity.getSubmitId()));
		param.setRoleUserMap(roleUserMap);
		//根据银行去掉节点
		List<String> list=new ArrayList<String>();
		if (!("SPDBGZ".equals(o2oEnterpriseZxEntity.getZxBank()) || "SPDBJN".equals(o2oEnterpriseZxEntity.getZxBank()))) { // 佣金跟自营模式不需要过平台总
			//s
			list.add(WorkFlowConstants.O2O_WF_CODE_QYZX_ZBZXSS1);
			list.add(WorkFlowConstants.O2O_WF_CODE_QYZX_TJR);
			list.add(WorkFlowConstants.O2O_WF_CODE_QYZX_ZBZXSS5);
			//excludeNodeCodeList
		}
		param.setExcludeNodeCodeList(list);
		param.setReferId(o2oEnterpriseZxEntity.getId());
		param.setReferCode(o2oEnterpriseZxEntity.getBillCode());
		param.setReferUrl(NewQYZxUrl); //企业征信详情
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType("E_CREDIT");
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(o2oEnterpriseZxEntity.getLtd());
		StringBuffer appliedDes = new StringBuffer("姓名:");
		appliedDes.append(o2oEnterpriseZxEntity.getCustomerName());
		appliedDes.append("，征信银行:"+o2oPubDdItemService.findPubdditemNameByCodeisall("BANKTYPEO2O", o2oEnterpriseZxEntity.getZxBank()));
		param.setAppliedDes(appliedDes.toString());
		logger.info("提交征信，参数有征信id：【{}】，征信编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
				o2oEnterpriseZxEntity.getId(),o2oEnterpriseZxEntity.getBillCode(),"E_CREDIT",param.getProcessType(),o2oEnterpriseZxEntity.getLtd(),appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			o2oEnterpriseZxEntity.setZxStatus(StatusContexts.WFTYPE_STATUS_RUN);
			o2oEnterpriseZxEntity.setSubmitId(user.getNo());
			o2oEnterpriseZxEntity.setSubmitName(user.getCname());
			o2oEnterpriseZxEntity.setSubmitDate(new Date());
			o2oEnterpriseZxService.update(o2oEnterpriseZxEntity);
			//o2oLoanapplyService.updateWorkFlowStatus(StatusContexts.O2O_ZX_BEGIN, o2oLoanapplyEntity.getLoanapplyNo());
			return BaseRestResult.info("提交成功").andRedirect(UrlHelper.build("/enterpriseZx/list"));
		} else {
			logger.error("提交企业征信失败，错误信息{}", modelResult.getDetailStack());
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
	}
	
	/**
	 * 提交新征信
	 * 
	 * @return
	 */
	@RequestMapping(value = "/newstartup")
	public BaseRestResult<String> newstartup(PayMentForm payform) {
		O2oZxEntity o2oZxEntity = o2oZxServiceImpl.getEntityById(payform.getLoanapplyNo());
		logger.info("贷款对象：{}", o2oZxEntity);
		O2oLoanUserEntityZx  o2oLoanUserEntityZx=o2oLoadUserZxServiceImpl.getEntityByZxNo(payform.getLoanapplyNo());
		
		if (!o2oDataListService.checkDataCode(o2oZxEntity.getId(), null)){
			return BaseRestResult.warn("上传附件未齐全");
		}
		
		if(o2oZxEntity.getZxBank()==null){
			return BaseRestResult.warn("请选择征信银行后，再启动流程");
		}
		
		if(!StatusContexts.O2O_BANKTYPE_BC.equals(o2oZxEntity.getZxBank())){
			Boolean isMothSelected =o2oZxServiceImpl.isMothSelectedZX(o2oLoanUserEntityZx.getDocumentNo(), o2oZxEntity.getZxBank());
			if(isMothSelected){
				return BaseRestResult.warn("一个自然月内在同一家银行仅能查询一次个人征信报告");
			}
		}
		
		boolean checkDataCode = o2oDataListService.checkDataCode(payform.getLoanapplyNo(), payform.getMaterId()); //check 申请材料是否上传齐全。
		if (checkDataCode) {
			WFRequestParam param = new WFRequestParam();
			param.setReferId(o2oZxEntity.getId());
			param.setReferCode(o2oZxEntity.getBillCode());
			param.setReferUrl(NewZxUrl);
			param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
			param.setProcessType(StatusContexts.WF_TYPE_CREDIT_INQUIRY);
			param.setProcessVersion("v1");
			User user = UserHolder.getUser();
			param.setAppliedby(user.getNo());
			param.setAppliedbyName(user.getCname());
			param.setOrgNo(o2oZxEntity.getLtd());
			//param.setReferUrl(backfeeUrl + "?billCode=" + o2oZxEntity.getId()+"&type=1");
			StringBuffer appliedDes = new StringBuffer("姓名:");
			appliedDes.append(o2oLoanUserEntityZx.getUserFullName());
			appliedDes.append("，客户类型:"+o2oPubDdItemService.findPubdditemO2ONameByCode("ZX_TYPE", o2oZxEntity.getZxType()));
			appliedDes.append("，征信银行:"+o2oPubDdItemService.findPubdditemNameByCodeisall("BANKTYPEO2O", o2oZxEntity.getZxBank()));
			param.setAppliedDes(appliedDes.toString());
			logger.info("提交征信，参数有征信id：【{}】，征信编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
					o2oZxEntity.getId(),o2oZxEntity.getBillCode(),ProcessTemplate.SYSTEM_MODULE_O2O,param.getProcessType(),o2oZxEntity.getLtd(),appliedDes.toString());
			ModelResult<Boolean> modelResult = workFlowService.instance(param);
			if (modelResult.isSuccess() && modelResult.getModel()) {
				o2oZxEntity.setZxStatus(StatusContexts.WFTYPE_STATUS_RUN);
				o2oZxEntity.setSubmitId(user.getNo());
				o2oZxEntity.setSubmitName(user.getCname());
				o2oZxEntity.setSubmitDate(new Date());
				o2oZxServiceImpl.update(o2oZxEntity);
				//o2oLoanapplyService.updateWorkFlowStatus(StatusContexts.O2O_ZX_BEGIN, o2oLoanapplyEntity.getLoanapplyNo());
				return BaseRestResult.info("提交成功").andRedirect(UrlHelper.build("/o2ozx/list"));
			} else {
				logger.error("提交征信失败，错误信息{}", modelResult.getDetailStack());
				return BaseRestResult.warn(modelResult.getErrMsg());
			}
		} else {
			return BaseRestResult.warn("附件上传未齐全,请编辑贷款信息");
		}
	}
	
	
	/**
	 * 提交征信
	 * 
	 * @return
	 */
	@RequestMapping(value = "/startup")
	public BaseRestResult<String> upload(PayMentForm payform) {
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(payform.getLoanapplyNo());
		logger.info("贷款对象：{}", o2oLoanapplyEntity);
		O2oLoanUserEntity  SpouseEntity=o2oLoanUserService.findSpouseId(o2oLoanapplyEntity.getLoanId(), o2oLoanapplyEntity.getLoanapplyNo());
		String code=null;
		if(SpouseEntity!=null){
			code="code";
			// 检查配偶信息
			//check是否编辑配偶关系
			//1.查询配偶有没存在 2.不存在 ：检测是否有新增配偶关系
			String  checkSpouse = checkSpouseZX(SpouseEntity.getLoanId());
			if(!checkSpouse.equals(StatusContexts.SUCCESS)){
				return BaseRestResult.warn(checkSpouse);
			}
		}
		if (!o2oDataListService.checkDataCode(o2oLoanapplyEntity.getLoanapplyNo(), code)){
			return BaseRestResult.warn("上传附件未齐全");
		}
		O2oLoanUserEntity  basicEntity = o2oLoanUserService.findById(o2oLoanapplyEntity.getLoanId(), o2oLoanapplyEntity.getLoanapplyNo());
		//检查借款人信息
		String  checkLoaner= checkZX(basicEntity, o2oLoanapplyEntity);
		if(!checkLoaner.equals(StatusContexts.SUCCESS)){
			return BaseRestResult.warn(checkLoaner);
		}
		//check贷款信息 
		String checkLoanApply = checkLoanApply(o2oLoanapplyEntity);
		if (!checkLoanApply.equals(StatusContexts.SUCCESS)) {
			return BaseRestResult.warn(checkLoanApply);
		}
		boolean checkDataCode = o2oDataListService.checkDataCode(payform.getLoanapplyNo(), payform.getMaterId()); //check 申请材料是否上传齐全。
		if (checkDataCode) {
			WFRequestParam param = new WFRequestParam();
			param.setReferId(o2oLoanapplyEntity.getLoanapplyNo());
			param.setReferCode(o2oLoanapplyEntity.getBillCode());
			param.setReferUrl(zxUrl);
			param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
			if(o2oLoanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_BK)){
				param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_CREDIT));
			}else{
				if(o2oLoanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_FQ)||o2oLoanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_EA)){
					param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_CREDI_FQ));
				}
				if(o2oLoanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_BP)||o2oLoanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_BP_JX)||o2oLoanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_SG)||o2oLoanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_YC)||o2oLoanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_SC)){
					param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_CREDI_BP));
				}
			}
			param.setProcessVersion("v1");
			User user = UserHolder.getUser();
			param.setAppliedby(user.getNo());
			param.setAppliedbyName(user.getCname());
			param.setOrgNo(o2oLoanapplyEntity.getLtd());
			StringBuffer appliedDes = new StringBuffer("借款人:");
			appliedDes.append(o2oLoanapplyService.findLoanUserEntity(o2oLoanapplyEntity.getLoanapplyNo(),o2oLoanapplyEntity.getLoanId()).getUserFullName());
			appliedDes.append("，申请金额:");
			java.text.DecimalFormat df=new java.text.DecimalFormat("0.00"); //格式化，保留两位小数 
			appliedDes.append(df.format(o2oLoanapplyEntity.getLoanaMount().doubleValue()));
			param.setAppliedDes(appliedDes.toString());
			logger.info("提交征信，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
					o2oLoanapplyEntity.getLoanapplyNo(),o2oLoanapplyEntity.getBillCode(),ProcessTemplate.SYSTEM_MODULE_O2O,param.getProcessType(),o2oLoanapplyEntity.getLtd(),appliedDes.toString());
			ModelResult<Boolean> modelResult = workFlowService.instance(param);
			if (modelResult.isSuccess() && modelResult.getModel()) {
//				o2oPayServiceImpl.updateWftypeStatus(o2oLoanapplyEntity.getLoanapplyNo(), StatusContexts.WFTYPE_ZX);
				o2oLoanapplyService.updateWorkFlowStatus(StatusContexts.O2O_ZX_BEGIN, o2oLoanapplyEntity.getLoanapplyNo());
				//启动财务审核流程
				if(o2oLoanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_BK)&&StatusContexts.OPERATION_MODEL_PTDB.equals(o2oLoanapplyEntity.getOperationModel())){
				// if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BK)){
					O2oFinanceFlowEntity entity = financeFlowService.getByLoanApplyno(payform.getLoanapplyNo());
					if (entity != null && entity.getFlowStatus().equals(StatusContexts.O2O_BANK_NEW)) {
						startUpFinance(payform);
					}
					if (entity == null) {
						startUpFinance(payform);
					}
				}
				return BaseRestResult.info("提交成功").andRefresh();
			} else {
				logger.error("提交征信失败，错误信息{}", modelResult.getDetailStack());
				return BaseRestResult.warn(modelResult.getErrMsg());
			}
		} else {
			return BaseRestResult.warn("附件上传未齐全,请编辑贷款信息");
		}
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               check贷款信息
	 *               </p>
	 * @author CXW
	 * @date 2017年7月10日 下午3:39:23
	 * @version V1.0
	 */
	public  String checkLoanApply(O2oLoanapplyEntity loan) {
		String result = "SUCCESS";
		if(StringUtil.isBlank(loan.getLoanType()) ){
			return "贷款类型不能为空，请编辑贷款信息";
		}
		if(StringUtil.isBlank(loan.getLtd()) ){
			return "经办平台不能为空，请编辑贷款信息";
		}
		if(StringUtil.isBlank(loan.getOperatorNo()) ){
			return "信贷经理不能为空，请编辑贷款信息";
		}
		if(StringUtil.isBlank(loan.getOperationModel()) ){
			return "经营模式不能为空，请编辑贷款信息";
		}
		if(StatusContexts.LOAN_TYPE_BK.equals(loan.getLoanType()) && StringUtil.isBlank(loan.getCustomerNo())){
			return "SD客户名称不能为空，请编辑贷款信息";
		}
		if((StatusContexts.LOAN_TYPE_BP.equals(loan.getLoanType()) || StatusContexts.LOAN_TYPE_BP_JX.equals(loan.getLoanType()) || StatusContexts.LOAN_TYPE_SG.equals(loan.getLoanType()) || StatusContexts.LOAN_TYPE_YC.equals(loan.getLoanType()) || StatusContexts.LOAN_TYPE_SC.equals(loan.getLoanType())) && StringUtil.isBlank(loan.getPartnerId())){
			return "渠道名称不能为空，请编辑贷款信息";
		}
	
		if(null == loan.getLoanaMount()){
			return "申请金额不能为空，请编辑贷款信息";
		}
		
		
		return result;
	}

	/**
	 * 提交财务审核
	 * 
	 * @return
	 */
	@RequestMapping(value = "/startup_finance")
	public BaseRestResult<String> startUpFinance(PayMentForm payform) {
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(payform.getLoanapplyNo());
		
		O2oFinanceFlowEntity entity = financeFlowService.getByLoanApplyno(payform.getLoanapplyNo());
		if (entity == null) {
			entity = new O2oFinanceFlowEntity();
			entity.setBillCode(loan.getBillCode());
			entity.setLoanapplyno(loan.getLoanapplyNo());
			entity.setFlowStatus(StatusContexts.O2O_BANK_NEW);
			entity.setRemark("提交财务审核，贷款id:" + loan.getLoanapplyNo());
			User user = UserHolder.getUser();
			entity.setStartupOperno(user.getNo());
			entity.setStartupOpername(user.getCname());
			financeFlowService.insert(entity);
		} 
		
		WFRequestParam param = new WFRequestParam();
		param.setReferId(loan.getLoanapplyNo());
		param.setReferCode(loan.getBillCode());
		param.setReferUrl(cwshUrl);
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_FINANCE_AUDIT));
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(loan.getLtd());
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(), loan.getLoanId()).getUserFullName());
		appliedDes.append("，申请金额:");
		java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); // 格式化，保留两位小数
		appliedDes.append(df.format(loan.getLoanaMount().doubleValue()));
		param.setAppliedDes(appliedDes.toString());
		logger.info("提交财务审核，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", loan.getLoanapplyNo(), loan.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), loan.getLtd(), appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess()&& modelResult.getModel()) {
			entity.setStartupTime(new Date());
			entity.setFlowStatus(StatusContexts.O2O_BANK_RUN);
//			o2oPayServiceImpl.updateWftypeStatus(loan.getLoanapplyNo(), StatusContexts.WFTYPE_FINANCE);
			financeFlowService.update(entity);
			return BaseRestResult.info("提交成功").andRefresh();
		} else {
			logger.error("提交征信失败，错误信息{}", modelResult.getDetailStack());
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
	}

	/**
	 * 提交内审 工作流
	 * 
	 * @return
	 */
	@RequestMapping("/submit")
	public BaseRestResult<String> sumform(com.eascs.admin.o2o.loan.form.PayMentForm payform) {
		
		com.eascs.admin.common.vo.ModelResult<Boolean> sumformCheck = payMentService.sumformCheck(payform);
		
		if(!sumformCheck.isSuccess()){
			return BaseRestResult.warn(sumformCheck.getErrMsg());
		}
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(payform.getLoanapplyNo());
		logger.info("提交内审单号为：{}", payform.getLoanapplyNo());
		HREmployeeAuditor auditor=employeeService.getAuditorWithNoAndType(loan.getOperatorNo(), "RM");
		WFRequestParam param = new WFRequestParam();
		param.setReferId(loan.getLoanapplyNo());
		param.setReferCode(loan.getBillCode());
		param.setReferUrl(nsUrl);
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BK)){
			param.setProcessType(ProcessTemplate.PROECESS_TYPE_INAUDIT);
		}else{
			if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_FQ)||loan.getLoanType().equals(StatusContexts.LOAN_TYPE_EA)){
				param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_INAUDIT_FQ));
			}
			if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BP) || loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BP_JX) || loan.getLoanType().equals(StatusContexts.LOAN_TYPE_SG) || loan.getLoanType().equals(StatusContexts.LOAN_TYPE_YC) || loan.getLoanType().equals(StatusContexts.LOAN_TYPE_SC)){
				param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_INAUDIT_BP));
			}
		}
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(loan.getLtd());
		//oan-10859 回购担保方选择S01163-O2O金融中心的贷款，审批流程去掉平台负责人的节点
		//if (StatusContexts.O2O_LTD_CODE_S01163.equals(loan.getLtdCode())) {
		//if (StatusContexts.O2O_LTD_CODE_S01163.equals(loan.getBuybackCode())) {
		List<String> list=new ArrayList<String>();
		if (StatusContexts.OPERATION_MODEL_ZY.equals(loan.getOperationModel())||StatusContexts.OPERATION_MODEL_YJ.equals(loan.getOperationModel())) { // 佣金跟自营模式不需要过平台总
			if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BK)){//终端贷
				list.add(StatusContexts.O2O_WF_CODE_NS_ZJL);
			}
			if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_FQ)||loan.getLoanType().equals(StatusContexts.LOAN_TYPE_EA)){ //分期贷
				list.add(StatusContexts.O2O_WF_CODE_NS_FQZJL);
			}
			if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BP)||loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BP_JX)||loan.getLoanType().equals(StatusContexts.LOAN_TYPE_SG)||loan.getLoanType().equals(StatusContexts.LOAN_TYPE_YC)||loan.getLoanType().equals(StatusContexts.LOAN_TYPE_SC)){ //品牌贷
				list.add(StatusContexts.O2O_WF_CODE_NS_BPZJL);
			}
			
			//excludeNodeCodeList
		}
		Map<String, List<String>> roleUserMap = new HashMap<>();  //指定流程节点由谁经办
		//区域经理
		if (auditor==null) {
			if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BK)){//终端贷
				list.add(StatusContexts.O2O_WF_CODE_NS_QYJLSPR);
			}else if (loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BP) || loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BP_JX) || loan.getLoanType().equals(StatusContexts.LOAN_TYPE_SG) || loan.getLoanType().equals(StatusContexts.LOAN_TYPE_YC) || loan.getLoanType().equals(StatusContexts.LOAN_TYPE_SC)) {
				list.add(StatusContexts.O2O_WF_CODE_NS_QYJLSPR_BP);
			}
		}else {
			roleUserMap.put(StatusContexts.ROLE_TYPE_QYJLSPR,Arrays.asList(auditor.getAuditorNo()));
		}
		
		//信贷经理
		roleUserMap.put(StatusContexts.ROLE_TYPE_NS_XDJL,Arrays.asList(loan.getOperatorNo()));
		param.setRoleUserMap(roleUserMap);
		param.setExcludeNodeCodeList(list);
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(),loan.getLoanId()).getUserFullName());
		appliedDes.append("，申请金额:");
		java.text.DecimalFormat df=new java.text.DecimalFormat("0.00"); //格式化，保留两位小数 
		appliedDes.append(df.format(loan.getLoanaMount().doubleValue()));
		param.setAppliedDes(appliedDes.toString());
		logger.info("提交内审，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
				loan.getLoanapplyNo(),loan.getBillCode(),ProcessTemplate.SYSTEM_MODULE_O2O,param.getProcessType(),loan.getLtd(),appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			logger.info("提交内审工作流成功,单号：{}，返回对象：{}", payform.getLoanapplyNo(), modelResult.getModel().toString());
			o2oLoanapplyService.updateWorkFlowStatus(StatusContexts.O2O_NS_BEGIN, payform.getLoanapplyNo());
			wfTypeStatusService.updatefindRUN(loan.getLoanapplyNo(), StatusContexts.WFTYPE_NS);
//			 o2oPayServiceImpl.updateWftypeStatus(loan.getLoanapplyNo(), StatusContexts.WFTYPE_NS);
			return BaseRestResult.info("提交成功").andRefresh();
		} else {
			logger.error("提交内审 工作流失败，错误信息{}", modelResult.getDetailStack());
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
	}

	/**
	 * 面签申报 流程
	 * 
	 * @param payform
	 * @return
	 */
	@RequestMapping("/submitApproval")
	public BaseRestResult<String> sumbitApproval(PayMentForm payform) {
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(payform.getLoanapplyNo());
		//送审银行为江西银行的单据提交面签申报不需要校验银行卡信息 
		if(!loan.getBankLoanName().equals(BankRate.BANK_JCB)){
			if (StringUtils.isEmpty(loan.getBankAccount()) || StringUtils.isEmpty(loan.getReceiveBank())) {
				return BaseRestResult.warn("请在《下载带数据合同》界面填写银行卡信息");
			}
		}
		
//		if (loan.getBankType().equals(BankRate.BANK_BC)) {
//			if (!o2oDataListService.checkCodeAttachment(loan.getLoanapplyNo(), FileTypeConstants.DALIST_TYPE_REFUND)) {
//				return BaseRestResult.warn("未找到相关借款合同信息，请等待中国银行返回借款合同，如有问题请联系管理员");
//			}
//		}
		/**
		 * 查询未完成还款单数，包含本单大于等于2则不能申报，小于2则可以申报
		 */
		//如果通过了特殊面签申报则不用check这一部分
		O2OSpecialInterview specialInterview =  o2OSpecialInterviewService.fingCLOFlow(loan.getLoanapplyNo());
		if(specialInterview ==null){
			int i = o2oLoanapplyService.getUserLoanCount(loan.getLoanId());// 查询为完成还款单数，包含本单大于等于2则不能申报，小于2则可以申报
			if (i >= 2) {
				return BaseRestResult.warn("借款人在新系统的上一笔贷款单尚未还款完，该笔贷款单不能发起申报");
			}
		}
		if (loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BK) || StatusContexts.LOAN_TYPE_BP.equals(loan.getLoanType()) || StatusContexts.LOAN_TYPE_BP_JX.equals(loan.getLoanType()) || StatusContexts.LOAN_TYPE_SG.equals(loan.getLoanType()) || StatusContexts.LOAN_TYPE_YC.equals(loan.getLoanType()) || StatusContexts.LOAN_TYPE_SC.equals(loan.getLoanType())) {
			/**
			 * 判断借款人及其配偶是否有逾期和代偿的单
			 */
			logger.info("AJAX加载系统借款人和配偶是否包含代偿:VO[{}]", payform.toString());
			logger.info("贷款编号：[{}]，用户ID为：[{}]", loan.getLoanapplyNo(),loan.getLoanId());
			// 代偿
			O2OSpecialInterview ishasSpecialInterview =  o2OSpecialInterviewService.queryEntity(loan.getLoanapplyNo());
			if(ishasSpecialInterview==null||!StatusContexts.O2O_BANK_CLO.equals(ishasSpecialInterview.getBillStatus()) ){
				int count1 = o2oLoanapplyService.findDCLoan(loan.getLoanapplyNo());
				if (count1 > 0) {
					return BaseRestResult.warn("借款人夫妻双方在系统中有终端贷/品牌贷 代偿，请先结清再发起面签申报");
				}
			}
		}
		/**
		 * http://tick.o2ojr.eascs.com/ticket/view/loan-11419 浦发广州分行校验【保证金管理费】流程是否结束
		 */
		/*if (!BankRate.BANK_GACZ.equals(loan.getBankLoanName())) {
			LoanapplyExpand expand=loanapplyExpandService.fingByBillCode(loan.getBillCode());
			if (expand!=null) {
				if (!"CLO".equals(expand.getBillStatus())) {
					return BaseRestResult.warn("提交的保证金管理费流程没有结束，不能申报！");
				}
			}else {
				return BaseRestResult.warn("没有提交保证金管理费流程，不能申报！");
			}
		}*/
		
	
		
			Integer num = loanapplyDubboService.isSpouseExsitNotHK(loan.getLoanId(), loan.getLoanapplyNo());
			if (num > 0) {
			
				return 	BaseRestResult.warn("该借款人的历史配偶有未结清的贷款单");

			}
		
		
		/**
		 * 校验表达是否保存填写
		 */
		String chekSbBd = chekSbBd(loan);
		if(!chekSbBd.equals(StatusContexts.SUCCESS)){
			return BaseRestResult.warn(chekSbBd);
		}
		
		Map<String, List<String>> roleUserMap = new HashMap<>();  //指定流程节点由谁经办
		logger.info("提交送审单号为：{}", payform.getLoanapplyNo());
		WFRequestParam param = new WFRequestParam();
		roleUserMap.put(StatusContexts.ROLE_TYPE_NS_XDJL,Arrays.asList(loan.getOperatorNo()));
		param.setRoleUserMap(roleUserMap);
		param.setReferId(loan.getLoanapplyNo());
		param.setReferCode(loan.getBillCode());
		param.setReferUrl("http://xxxx.eascs.com/getDetail");
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BK)||StatusContexts.LOAN_TYPE_BP.equals(loan.getLoanType())||StatusContexts.LOAN_TYPE_BP_JX.equals(loan.getLoanType())||StatusContexts.LOAN_TYPE_SG.equals(loan.getLoanType())||StatusContexts.LOAN_TYPE_YC.equals(loan.getLoanType())||StatusContexts.LOAN_TYPE_SC.equals(loan.getLoanType())){
			param.setProcessType(ProcessTemplate.PROECESS_TYPE_BANK_REPORT);
		}else{
			if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_FQ)||loan.getLoanType().equals(StatusContexts.LOAN_TYPE_EA)){
				param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_BANK_REPORT_FQ));
			}
		}
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(loan.getLtd());
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(),loan.getLoanId()).getUserFullName());
		appliedDes.append("，批复金额:");
		java.text.DecimalFormat df=new java.text.DecimalFormat("0.00"); //格式化，保留两位小数 
		appliedDes.append(df.format(loan.getEaMount().doubleValue()));
		appliedDes.append("，送审银行：");
		appliedDes.append(o2oPubDdItemService.findPubdditemNameByCodeisall("BANKTYPEO2O", loan.getBankLoanName()));
		param.setAppliedDes(appliedDes.toString());
		logger.info("提交面签申报，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
				loan.getLoanapplyNo(),loan.getBillCode(),ProcessTemplate.SYSTEM_MODULE_O2O,param.getProcessType(),loan.getLtd(),appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			logger.info("提交银行申报工作流成功，单号：{}，返回对象：{}", payform.getLoanapplyNo(), modelResult.getModel().toString());
			o2oLoanapplyService.updateWorkFlowStatus(StatusContexts.O2O_SB_BEGIN, payform.getLoanapplyNo());
			wfTypeStatusService.updatefindRUN(loan.getLoanapplyNo(), StatusContexts.WFTYPE_BRT);
//			 o2oPayServiceImpl.updateWftypeStatus(loan.getLoanapplyNo(), StatusContexts.WFTYPE_BRT);
			return BaseRestResult.info("提交成功").andRefresh();
		} else {
			logger.error("面签申报 流程启动失败，错误信息{}", modelResult.getDetailStack());
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
	}
	
	public String chekSbBd(O2oLoanapplyEntity loanEntity){
		logger.info("信贷经理表单URL：[{}]", WorkFlowConstants.BRT_FROM_ID_CONTRACT_URL);
		if (StringUtil.isEmpty(loanEntity.getContractFlag())) {
			return "合同未齐备，请点击编辑面签资料";
		}
		if (!o2oDataListService.checkCodeAttachment(loanEntity.getLoanapplyNo(), FileTypeConstants.DALIST_TYPE_CONTRACT)) {
			return "面签材料未上传，请点击编辑面签资料";
		}
		if (StatusContexts.O2O_NO.equals(loanEntity.getContractFlag())) {
			return "合同未齐备，不能发起流程，请点击编辑面签资料";
		}
		return StatusContexts.SUCCESS;
	}

	/**
	 * 提交 收取管理费和保证金流程
	 * 
	 * @param payform
	 * @return
	 */
	@RequestMapping("/submitBzj")
	public BaseRestResult<String> order(PayMentForm payform) {
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(payform.getLoanapplyNo());
		logger.info("提交收取管理费和保证金流程单号为：{}", payform.getLoanapplyNo());
//		if(loan.getBankLoanName().equals(StatusContexts.O2O_BANKTYPE_GACZ)){
//			if(!loan.getWfType().equals(StatusContexts.O2O_FK_END)){ 
//				return BaseRestResult.warn("请在面签提报流程结束后发起");
//			}
//		}
		
		/**
		 * 收取保证金管理费流程只能有一个，一次性缴清，如果有运行中，已经完成的状态的话，就没有必要再次在去启动流程
		 */
		LoanapplyExpand chekLoanapplyExpand = loanapplyExpandService.queryLoanapplyNo(payform.getLoanapplyNo());
		LoanapplyExpandDetail loanapplyExpandDetail=loanapplyExpandDetailService.queryDetail(chekLoanapplyExpand.getId());
		if(loanapplyExpandDetail!=null){
			loanapplyExpandDetailService.delete(loanapplyExpandDetail.getId());
			logger.info("启动保证金删除中间表数据,贷款单号：[{}],id[{}]", loanapplyExpandDetail.getBillCode(),loanapplyExpandDetail.getId());
		}
		if(!chekLoanapplyExpand.getBillStatus().equals(StatusContexts.O2O_NEW)){
			logger.info("单号：{}，保证金工作流已经启动，请勿重复启动。", payform.getLoanapplyNo());
			return BaseRestResult.warn("保证金管理费流程已启动，请勿重复启动。");
		}
		
		WFRequestParam param = new WFRequestParam();
		Map<String, List<String>> roleUserMap = new HashMap<>();  //指定流程节点由谁经办
		roleUserMap.put(StatusContexts.ROLE_TYPE_NS_XDJL,Arrays.asList(loan.getOperatorNo()));
		param.setRoleUserMap(roleUserMap);
		param.setReferId(loan.getLoanapplyNo());
		param.setReferCode(loan.getBillCode());
		param.setReferUrl(sbzjUrl);
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_BK)||StatusContexts.LOAN_TYPE_BP.equals(loan.getLoanType())||StatusContexts.LOAN_TYPE_BP_JX.equals(loan.getLoanType())||StatusContexts.LOAN_TYPE_SG.equals(loan.getLoanType())||StatusContexts.LOAN_TYPE_YC.equals(loan.getLoanType())||StatusContexts.LOAN_TYPE_SC.equals(loan.getLoanType())){
			param.setProcessType(ProcessTemplate.PROECESS_TYPE_DEPOSIT);
		}else{
			if(loan.getLoanType().equals(StatusContexts.LOAN_TYPE_FQ)||loan.getLoanType().equals(StatusContexts.LOAN_TYPE_EA)){
				param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_DEPOSIT_FQ));
			}
		}
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		if (null != user) {
			param.setAppliedby(user.getNo());
			param.setAppliedbyName(user.getCname());
		} else {
			param.setAppliedby("1");
			param.setAppliedbyName("系统管理员");
		}
		param.setOrgNo(loan.getLtd());
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(),loan.getLoanId()).getUserFullName());
		appliedDes.append("，EA批复金额:");
		java.text.DecimalFormat df=new java.text.DecimalFormat("0.00"); //格式化，保留两位小数 
		appliedDes.append(df.format(loan.getEaMount()));
		param.setAppliedDes(appliedDes.toString());
		logger.info("提交 收取管理费和保证金流程，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
				loan.getLoanapplyNo(),loan.getBillCode(),ProcessTemplate.SYSTEM_MODULE_O2O,param.getProcessType(),loan.getLtd(),appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			logger.info("提交保证金工作流成功，单号：{}，返回对象：{}", payform.getLoanapplyNo(), modelResult.getModel().toString());
			LoanapplyExpand loanapplyExpand = loanapplyExpandService.queryLoanapplyNo(loan.getLoanapplyNo());
			loanapplyExpand.setBillStatus(StatusContexts.BZJ_STATUS_RUN);
			loanapplyExpand.setLoanapply_no(loan.getLoanapplyNo());
			loanapplyExpandService.updateWorkFlow(loanapplyExpand);
			return BaseRestResult.info("提交成功").andRefresh();
		} else {
			logger.error("提交 收取管理费和保证金流程失败，错误信息{}", modelResult.getDetailStack());
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
	}

	/**
	 * 启动付费流程
	 * 
	 * @param payform
	 * @return
	 */
	@RequestMapping("/startpay")
	public BaseRestResult<String> startPay(PayMentForm payform) {
		logger.info("申请付费流程单号为：{}", payform.getLoanapplyNo());
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(payform.getLoanapplyNo());
		O2oLoanUserEntity loanUserEntity = o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(), loan.getLoanId());
		ModelResult<Boolean> modelResult = o2oPayServiceImpl.startPayFlow(loan, loanUserEntity.getUserFullName());
		if (modelResult.isSuccess() && modelResult.getModel()) {
			logger.info("内审完成启动付款流程数据成功，贷款单号为：{}", payform.getLoanapplyNo());
			O2oPayEntity o2oPayEntity = o2oPayServiceImpl.findEntityByLoanapplyId(loan.getLoanapplyNo());
			if(null!=o2oPayEntity){
				o2oPayEntity.setSubmitTime(new Date());
				o2oPayEntity.setSubmitUser(loan.getOperatorNo());
				o2oPayEntity.setBillStatus(StatusContexts.O2O_BANK_RUN);
				o2oPayEntity.setLastUpdateTime(new Date());
				
				o2oPayServiceImpl.updateEntityById(o2oPayEntity);
				logger.info("内审完成启动付款流程数据成功，贷款单号为：{},更新付款数据成功", loan.getLoanapplyNo());
			}
			return BaseRestResult.info("提交成功").andRefresh();
		} else {
			logger.error("内审完成启动付款流程数据成功，贷款单号为：{},失败原因：{}", loan.getLoanapplyNo(), modelResult.getDetailStack());
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
	}
	
	/**
	 * 启动归档
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/file")
	public BaseRestResult<String> placeOnFile(String loanapplyNo){
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(loanapplyNo);
		WFRequestParam param = new WFRequestParam();
		param.setReferId(loan.getLoanapplyNo());
		param.setReferCode(loan.getBillCode());
		param.setReferUrl("http://xxxx.eascs.com/getDetail");
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_PLACE_ON_FILE));
		param.setProcessVersion("v1");
		param.setAppliedby(loan.getOperatorNo());
		param.setAppliedbyName(loan.getOperatorName());
		param.setOrgNo(loan.getLtd());
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(),loan.getLoanId()).getUserFullName());
		appliedDes.append("，放款金额:");
		java.text.DecimalFormat df=new java.text.DecimalFormat("0.00"); //格式化，保留两位小数 
		BigDecimal loanAmount=new BigDecimal(0);
		if ("EA".equals(loan.getLoanType())||"FQ".equals(loan.getLoanType())) {
			loanAmount = service.findDataByBillCode(loan.getBillCode()).getLoanAmount();
		}else{
			loanAmount = o2oLoanService.queryBillCode(loan.getBillCode()).getLoanAmount();
		}
		appliedDes.append(df.format(loanAmount));
		param.setAppliedDes(appliedDes.toString());
		logger.info("启动归档，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
				loan.getLoanapplyNo(),loan.getBillCode(),ProcessTemplate.SYSTEM_MODULE_O2O,param.getProcessType(),loan.getLtd(),appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			logger.info("提交启动归档成功，单号：{}，返回对象：{}",loanapplyNo, modelResult.getModel().toString());
			o2oLoanapplyService.updateOnfileStatus(StatusContexts.O2O_BANK_RUN, loan.getLoanapplyNo());
			return BaseRestResult.info("启动成功").andRefresh();
		} else {
			logger.error("错误信息{}", modelResult.getDetailStack());
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
	}
	
	public String checkSpouseZX(String id){
		CustomerEntity basicEntity = customerService.queryCustomerEntityByCustomerId(id);
//		CustomerBasicInfo customerBasicInfo = o2oLoanapplyService.getCustomerEntityById(id);//查询借款人扩展信息
		//boolean sex = StringUtil.isEmpty(basicEntity.getSex());
		boolean familyName = StringUtil.isEmpty(basicEntity.getCustomerFamilyName()); //配偶姓
		boolean givenName = StringUtil.isEmpty(basicEntity.getCustomerGivenName()); //配偶名
		boolean idType = StringUtil.isEmpty(basicEntity.getIdType());  //配偶证件类型
		boolean idNumber = StringUtil.isEmpty(basicEntity.getIdNumber()); //配偶证件号码
		boolean mobileNumber = StringUtil.isEmpty(basicEntity.getMobileNumber()); //联系电话
		boolean licenseExpirationDate = StringUtil.isEmpty(basicEntity.getLicenseExpirationDate()); //证件到期日
		boolean MaritalStatus = StringUtil.isEmpty(basicEntity.getMaritalStatus()); //婚姻状况
		if (familyName) {
			return  "配偶姓不能为空，请编辑借款人信息";
		}
		if (givenName) {
			return  "配偶名不能为空，请编辑借款人信息";
		}
		if (idType) {
			return  "配偶证件类型不能为空，请编辑借款人信息";
		}
		if (idNumber) {
			return  "配偶证件号码不能为空，请编辑借款人信息";
		}
		if (mobileNumber) {
			return  "配偶联系电话不能为空，请编辑借款人信息";
		}
		if (licenseExpirationDate) {
			return  "配偶证件到期日不能为空，请编辑借款人信息";
		}
		if (MaritalStatus) {
			return  "配偶婚姻状况不能为空，请编辑借款人信息";
		}
		
		return StatusContexts.SUCCESS;
		
	}
	
	public String checkZX(O2oLoanUserEntity  basicEntity, O2oLoanapplyEntity o2oLoanapplyEntity){
		if(basicEntity == null){
			logger.info("获取客户信息失败！或是客户不存在");
			return "获取客户信息失败！或是客户不存在";
		}else{
			logger.info("获取客户信息结果：customer：{}", basicEntity.toString());
		}
		CustomerBasicInfo customerBasicInfo = o2oLoanapplyService.getCustomerEntityById(basicEntity.getId());//查询借款人扩展信息
		boolean familyName = StringUtil.isEmpty(basicEntity.getUserSurName()); //借款人姓
		boolean givenName = StringUtil.isEmpty(basicEntity.getUserName()); //借款人名
		boolean idType = StringUtil.isEmpty(basicEntity.getDocumentType());  //证件类型
		boolean idNumber = StringUtil.isEmpty(basicEntity.getDocumentNo()); //证件号码
		boolean licenseExpirationDate = StringUtil.isEmpty(customerBasicInfo.getLicenseExpirationDate()); //证件到期日
		//boolean MaritalStatus = StringUtil.isEmpty(customerBasicInfo.getMaritalStatus()); //婚姻状况
		boolean customerName =  StringUtils.isBlank(o2oLoanapplyEntity.getCustomeRname()); //客户名称
		boolean mobileNumber = StringUtil.isEmpty(basicEntity.getUserPhone()); //联系电话
		boolean customerSd =  StringUtils.isBlank(o2oLoanapplyEntity.getCustomerNo());//客户sd号
		
		if (familyName) {
			logger.info("借款人姓不能为空，请编辑借款人信息");
			return  "借款人姓不能为空，请编辑借款人信息";
		}
		if (givenName) {
			logger.info("借款人名不能为空，请编辑借款人信息");
			return  "借款人名不能为空，请编辑借款人信息";
		}
		if (idType) {
			logger.info("借款人证件类型不能为空，请编辑借款人信息");
			return  "借款人证件类型不能为空，请编辑借款人信息";
		}
		if (idNumber) {
			logger.info("借款人证件号码不能为空，请编辑借款人信息");
			return  "借款人证件号码不能为空，请编辑借款人信息";
		}
		if (licenseExpirationDate) {
			logger.info("证件到期日不能为空，请编辑借款人信息");
			return  "证件到期日不能为空，请编辑借款人信息";
		}
		//if (MaritalStatus) {
		//	return  "借款人婚姻状况不能为空，请编辑借款人信息";
		//}
//		if (null==custmenrList || custmenrList.isEmpty()) {
//			return  "借款人合作平台不能为空，请编辑借款人信息";
//		}
		if (mobileNumber) {
			logger.info("借款人联系电话不能为空，请编辑借款人信息");
			return  "借款人联系电话不能为空，请编辑借款人信息";
		}
		if(!StatusContexts.LOAN_TYPE_BP.equals(o2oLoanapplyEntity.getLoanType())&&!StatusContexts.LOAN_TYPE_BP_JX.equals(o2oLoanapplyEntity.getLoanType())&&!StatusContexts.LOAN_TYPE_SG.equals(o2oLoanapplyEntity.getLoanType())&&!StatusContexts.LOAN_TYPE_YC.equals(o2oLoanapplyEntity.getLoanType())&&!StatusContexts.LOAN_TYPE_SC.equals(o2oLoanapplyEntity.getLoanType())){
			if (customerName) {
				logger.info("借款人客户名称不能为空，请编辑借款人信息");
				return  "借款人客户名称不能为空，请编辑借款人信息";
			}
			if (customerSd) {
				logger.info("借款人客户号不能为空，请编辑借款人信息");
				return  "借款人客户号不能为空，请编辑借款人信息";
			}
		}
		
		return StatusContexts.SUCCESS;
		
		
	}
	
	
	
	/**
	 * 
	 * 加签补充内审资料
	 * 
	 * @return
	 */
	@RequestMapping("/jqUpload")
	public HtmlRestResult otherUpload(ZXPTCWForm zXPTCWForm) {
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(zXPTCWForm.getReferId());
		List<Button> buttons =buildButtons( zXPTCWForm);
		ViewContext.put("buttons", buttons);
		ViewContext.put("datalistInfo", getDatalistInfo(zXPTCWForm.getReferId(),FileTypeConstants.DALIST_TYPE_JQ_NSFJ));
		ViewContext.put("loan", loan);
		ViewContext.put("zXPTCWForm", zXPTCWForm);
		ViewContext.put("pageResult", getDatalistInfo(zXPTCWForm.getReferId(),FileTypeConstants.DALIST_TYPE_DCWD));// 个人附件
		return new HtmlRestResult("/detail/jqnszlUpload");
	}
	
	/**
	 * 根据贷款单号，还有附件类型，获取附件列表
	 * @param loanapplyNo
	 * @return
	 */
	public PaginationInfo getDatalistInfo(String loanapplyNo,String uploadType){
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + uploadType + "'");
		String titles[] = {"附件类型","文件名", "提交人", "提交时间","更新时间"};
		 // AjaxConfirmButton[] dealButton=null;
		// dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
		Button[] titleButtons = new Button[] {null,ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo datalistInfo = new PaginationInfo(pageResult, titles, "/loanUser/loanudpate");
		datalistInfo.setTitleButtons(titleButtons);
		//datalistInfo.setMoreButtons(dealButton);
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(1);
		datalistInfo.setBuildRowNumber(true);
		return datalistInfo;
	}
	
	/**
	 * 根据流程编号，流程节点code，以及贷款编号获取应该显示的按钮列表
	 * @param zXPTCWForm
	 * @return
	 */
	public List<Button> buildButtons(ZXPTCWForm zXPTCWForm) {
		List<Button> buttons = new ArrayList<>();
		if (ProcessTemplate.PROECESS_TYPE_INAUDIT.equals(zXPTCWForm.getWfType())||ProcessTemplate.PROECESS_TYPE_INAUDIT_FQ.equals(zXPTCWForm.getWfType())||ProcessTemplate.PROECESS_TYPE_INAUDIT_BP.equals(zXPTCWForm.getWfType())) {
			buttons.add(ButtonHelper.createFileUpLoadButton("补充内审资料", "/loanrest/othfile/JQNSFJ/" + zXPTCWForm.getReferId()));
			buttons.add(ButtonHelper.createFileUpLoadButton("上传调查文档", "/loanrest/othfile/DCWD/" + zXPTCWForm.getReferId()));
		} 
		return buttons;
	}
	
	
	
	/**
	 * 提交征信准入流程
	 * 
	 * @return
	 */
	@RequestMapping(value = "/zxzrstartup")
	public BaseRestResult<String> zxzrstartup(PayMentForm payform) {
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(payform.getLoanapplyNo());
		logger.info("贷款对象：{}", o2oLoanapplyEntity);
		O2oLoanUserEntity SpouseEntity = o2oLoanUserService.findSpouseId(o2oLoanapplyEntity.getLoanId(),
				o2oLoanapplyEntity.getLoanapplyNo());
		if (SpouseEntity != null) {

			if (StringUtil.isEmpty(SpouseEntity.getZxNo())) {
				return BaseRestResult.warn("请选择配偶的征信报告");
			}
			O2oZxEntity mateZx = o2oZxServiceImpl.getEntityById(SpouseEntity.getZxNo());
			if (!"CLO".equals(mateZx.getZxStatus())) {
				return BaseRestResult.warn("选择的配偶的征信报告流程未结束");
			}
			
			O2oLoanUserEntityZx o2oLoanUserMateEntityZx = o2oLoadUserZxServiceImpl.getEntityByZxNo(SpouseEntity.getZxNo());

			if (o2oLoanUserMateEntityZx.getZxDate() != null) {
				boolean flag = isValid(o2oLoanUserMateEntityZx.getZxDate(), 30);
				if (!flag) {
					return BaseRestResult.warn("选择的配偶的征信报告已经超过30天有效期");
				}
			}
			
		/*	boolean mateFlag=o2oZxServiceImpl.bcIsSelectedByOther(payform.getLoanapplyNo(), SpouseEntity.getZxNo());
			if(mateFlag){
				return BaseRestResult.warn(o2oLoanUserMateEntityZx.getUserFullName()+"的征信报告已被其他单据关联过，无法再次关联");
			}*/
			
			if (mateZx.getZxBank().equals("BC")) {
				// 客户类型是否符合一致
				boolean typeFlag = o2oZxServiceImpl.bcIsSelectedByCustomerType(payform.getLoanapplyNo(),
						SpouseEntity.getZxNo(), "ZX_PO");
				if (typeFlag) {
					return BaseRestResult.warn("配偶"+o2oLoanUserMateEntityZx.getUserFullName() + "以借款人身份查询的中行征信报告，无法关联");
				}
			}
			
			// 检查配偶信息
			// check是否编辑配偶关系
			// 1.查询配偶有没存在 2.不存在 ：检测是否有新增配偶关系
			String checkSpouse = checkSpouseZX(SpouseEntity.getLoanId());
			if (!checkSpouse.equals(StatusContexts.SUCCESS)) {
				return BaseRestResult.warn(checkSpouse);
			}
		}
		/*
		 * if
		 * (!o2oDataListService.checkDataCode(o2oLoanapplyEntity.getLoanapplyNo(
		 * ), code)){ return BaseRestResult.warn("上传附件未齐全"); }
		 */
		O2oLoanUserEntity basicEntity = o2oLoanUserService.findById(o2oLoanapplyEntity.getLoanId(),
				o2oLoanapplyEntity.getLoanapplyNo());
		// 检查借款人信息
		String checkLoaner = checkZX(basicEntity, o2oLoanapplyEntity);
		if (!checkLoaner.equals(StatusContexts.SUCCESS)) {
			return BaseRestResult.warn(checkLoaner);
		}

		if (StringUtil.isEmpty(basicEntity.getZxNo())) {
			return BaseRestResult.warn("请选择借款人的征信报告");
		}

		O2oZxEntity userZx = o2oZxServiceImpl.getEntityById(basicEntity.getZxNo());
		if (!"CLO".equals(userZx.getZxStatus())) {
			return BaseRestResult.warn("选择的借款人的征信报告流程未结束");
		}

		O2oLoanUserEntityZx o2oLoanUserEntityZx = o2oLoadUserZxServiceImpl.getEntityByZxNo(basicEntity.getZxNo());

		if (o2oLoanUserEntityZx.getZxDate() != null) {
			boolean flag = isValid(o2oLoanUserEntityZx.getZxDate(), 30);
			if (!flag) {
				return BaseRestResult.warn("选择的借款人的征信报告已经超过30天有效期");
			}
		}
		
		// 是否被其他单款单关联
	/*	boolean flag = o2oZxServiceImpl.bcIsSelectedByOther(payform.getLoanapplyNo(), basicEntity.getZxNo());
		if (flag) {
			return BaseRestResult.warn(o2oLoanUserEntityZx.getUserFullName() + "的征信报告已被其他单据关联过，无法再次关联");
		}*/

		if (userZx.getZxBank().equals("BC")) {
			// 客户类型是否符合一致
			boolean typeFlag = o2oZxServiceImpl.bcIsSelectedByCustomerType(payform.getLoanapplyNo(),
					basicEntity.getZxNo(), "ZX_JKR");
			if (typeFlag) {
				return BaseRestResult.warn("借款人"+o2oLoanUserEntityZx.getUserFullName() + "以配偶身份查询的中行征信报告，无法关联");
			}

		}
		// check贷款信息
		String checkLoanApply = checkLoanApply(o2oLoanapplyEntity);
		if (!checkLoanApply.equals(StatusContexts.SUCCESS)) {
			return BaseRestResult.warn(checkLoanApply);
		}

		WFRequestParam param = new WFRequestParam();
		param.setReferId(o2oLoanapplyEntity.getLoanapplyNo());
		param.setReferCode(o2oLoanapplyEntity.getBillCode());
		param.setReferUrl(zxUrl);
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType("PROCESS_ACCESS");
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(o2oLoanapplyEntity.getLtd());
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(o2oLoanapplyService
				.findLoanUserEntity(o2oLoanapplyEntity.getLoanapplyNo(), o2oLoanapplyEntity.getLoanId())
				.getUserFullName());
		appliedDes.append("，申请金额:");
		java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); // 格式化，保留两位小数
		appliedDes.append(df.format(o2oLoanapplyEntity.getLoanaMount().doubleValue()));
		param.setAppliedDes(appliedDes.toString());
		logger.info("提交征信准入，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】",
				o2oLoanapplyEntity.getLoanapplyNo(), o2oLoanapplyEntity.getBillCode(),
				ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), o2oLoanapplyEntity.getLtd(),
				appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			o2oLoanapplyService.updateWorkFlowStatus(StatusContexts.O2O_ZX_BEGIN, o2oLoanapplyEntity.getLoanapplyNo());
			wfTypeStatusService.updatefindRUN(o2oLoanapplyEntity.getLoanapplyNo(), StatusContexts.WFTYPE_ZX);
			// 启动财务审核流程
			if (o2oLoanapplyEntity.getLoanType().equals(StatusContexts.LOAN_TYPE_BK)
					&& StatusContexts.OPERATION_MODEL_PTDB.equals(o2oLoanapplyEntity.getOperationModel())) {
				O2oFinanceFlowEntity entity = financeFlowService.getByLoanApplyno(payform.getLoanapplyNo());
				if (entity != null && entity.getFlowStatus().equals(StatusContexts.O2O_BANK_NEW)) {
					startUpFinance(payform);
				}
				if (entity == null) {
					startUpFinance(payform);
				}
			}
			return BaseRestResult.info("提交成功").andRefresh();
		} else {
			logger.error("提交征信准入失败，错误信息{}", modelResult.getDetailStack());
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
	}

	/**
	 * @Title: isValid
	 * @Description: 判断是否在30天有效期内
	 * @author 张庆奇
	 * @param dt1
	 * @param day
	 * @return
	 * @return boolean
	 * @throws
	 * @date 2017年10月16日 上午9:59:51
	 */
	public boolean isValid(Date dt1, int day) {
		boolean flag = true;
		Calendar now = Calendar.getInstance();
		now.setTime(new Date());
		now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
		Date dt2 = now.getTime();

		if (dt1.getTime() < dt2.getTime()) {
			System.out.println("dt1在dt2后");
			flag = false;
		}
		return flag;
	}
	

}
